from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import pymysql
from typing import List
from fastapi import Query
from fastapi import Request
from fastapi import Path
from datetime import datetime

app = FastAPI()

# 允许跨域，便于 React 前端本地开发调试
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境建议指定域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 公共常量配置
DB_CONFIG = {
    "host": "localhost",
    "user": "root",
    "password": "root@200",
    "database": "database_ai_product",
    "cursorclass": pymysql.cursors.DictCursor
}

PRODUCT_RANK_TYPE_DAY = "DAY"         # 取天级数据
PRODUCT_SOURCE_PH = "ProductHunt"    # 取PD数据

# 状态码和状态信息统一配置
RESPONSE_CODE = {
    "SUCCESS": 0,
    "PARAM_ERROR": 1,
    "DB_ERROR": 2
}
RESPONSE_MSG = {
    "SUCCESS": "success",
    "PARAM_ERROR": "参数错误",
    "DB_ERROR": "数据库查询异常"
}

def get_db_connection():
    return pymysql.connect(**DB_CONFIG)

@app.get("/api/daily_products/{date:path}")
def get_daily_products(
    date: str = Path(
        ...,
        regex="^\d{4}/\d{1,2}/\d{1,2}$",
        description="日期，格式为YYYY/MM/DD，例如2025/4/24"
    )
):
    try:
        date_obj = datetime.strptime(date, "%Y/%m/%d")
        date_str = date_obj.strftime("%Y-%m-%d")
    except ValueError:
        return {
            "code": RESPONSE_CODE["PARAM_ERROR"],
            "msg": RESPONSE_MSG["PARAM_ERROR"] + "，应为YYYY/M/D或YYYY/MM/DD",
            "data": []
        }

    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            sql = """
                SELECT * FROM ai_products
                WHERE product_rank_date = %s AND product_rank_type = %s AND product_source = %s
            """
            print("执行SQL:", sql)
            print("参数:", (date_str, PRODUCT_RANK_TYPE_DAY, PRODUCT_SOURCE_PH))
            cursor.execute(sql, (date_str, PRODUCT_RANK_TYPE_DAY, PRODUCT_SOURCE_PH))
            result = cursor.fetchall()
        return {
            "code": RESPONSE_CODE["SUCCESS"],
            "msg": RESPONSE_MSG["SUCCESS"],
            "data": result
        }
    except Exception as e:
        return {
            "code": RESPONSE_CODE["DB_ERROR"],
            "msg": RESPONSE_MSG["DB_ERROR"] + f": {str(e)}",
            "data": []
        }
    finally:
        conn.close()